package com.yakaten.service;

import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;

public class HtmlClient {

	/** 接続リトライ */
	protected static final int RETRY = 2;

	/** 接続タイムアウト/リードタイムアウト */
	protected static final int TIMEOUT = 10 * 1000;

	protected static final String DEFAULT_ENCODING = "UTF-8";

	public StringBuffer execute(String url) throws ClientProtocolException, IOException {
		return execute(url, null, 0, null, null, RETRY, TIMEOUT,
				DEFAULT_ENCODING);
	}

	public StringBuffer execute(String url, String encoding) throws ClientProtocolException, IOException {
		return execute(url, null, 0, null, null, RETRY, TIMEOUT, encoding);
	}

	public StringBuffer execute(String url, String proxyHost,
			int proxyPort, String userName, String password, int retry,
			int timeout, String encoding) throws ClientProtocolException, IOException {
		// インスタンス生成
		DefaultHttpClient client = new DefaultHttpClient();

		// set proxy
		if (proxyHost != null && proxyHost.trim().length() > 0 && proxyPort > 0) {
			HttpHost proxy = new HttpHost("proxysv", 80);
			client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
					proxy);
		}

		// set Auth
		if (userName != null && userName.trim().length() > 0) {
			client.getCredentialsProvider().setCredentials(
					new AuthScope(proxyHost, proxyPort),
					new UsernamePasswordCredentials(userName, password));
		}

		HttpGet httpget = new HttpGet(url);

		StringBuffer htmlBuffer = null;
		try {
			HttpResponse response = client.execute(httpget);
			InputStreamReader isr = new InputStreamReader(response.getEntity()
					.getContent(), encoding);
			int contents;
			htmlBuffer = new StringBuffer();
			while ((contents = isr.read()) != -1) {
				htmlBuffer.append((char) contents);
			}
		}  finally {
			client.getConnectionManager().shutdown();
		}
		return htmlBuffer;
	}

}
